package com.mock.ems.controller;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.mock.base.util.CollectionUtil;
import com.mock.base.util.StringUtil;
import com.mock.ems.common.JsonResult;
import com.mock.ems.utils.TGlCateUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ItemSortController extends Controller {

    public void index(){renderJsp("/page/itemsort/list.jsp");}

    public void pagination(){

        int limit = getParaToInt("limit");
        int offset = getParaToInt("offset");
        int pageNumber = (offset / limit) + 1;

        String selectSql = "select *";
        StringBuilder exceptSelectSQL = new StringBuilder(" from t_gl_cate where type_key_ = 'ProductCate'");

        List<Object> params = new ArrayList<Object>();

        String name = getPara("name_");
        if(StringUtil.isNotEmpty(name)){
            exceptSelectSQL.append(" and name_ like ?");
            params.add("%"+name.trim()+"%");
        }

        exceptSelectSQL.append(" order by id_ desc");

        Page<Record> page = Db.paginate(pageNumber,limit,selectSql,exceptSelectSQL.toString(),params.toArray());

        if(CollectionUtil.isNotEmpty(page.getList())){
            page.getList().stream().forEach(item->{
                String parentId = item.getStr("parent_id_");
                if(StringUtil.isEmpty(parentId)){
                    item.set("parentName","无");
                }else{
                    Record parent = Db.findById("t_gl_cate","id_",parentId);
                    if(parent == null){
                        item.set("parentName","未知");
                    }else{
                        item.set("parentName",parent.getStr("name_"));
                    }
                }
            });
        }

        Map<String, Object> returnMap = new HashMap<String, Object>();
        returnMap.put("total", page.getTotalRow());
        returnMap.put("rows", page.getList());
        renderJson(returnMap);
    }

    public void edit(){

        String id_ = getPara("id");
        List<Record> parentList = Db.find("select * from t_gl_cate where depth_ = 1 and type_key_ = 'ProductCate'");
        setAttr("parentList",parentList);
        if(StringUtil.isNotEmpty(id_)){
            Record record = Db.findById("t_gl_cate","id_",id_);
            setAttr("record",record);
        }

        renderJsp("/page/itemsort/edit.jsp");
    }

    @Before(Tx.class)
    public void save(){

        String id_ = getPara("id");
        Record record = new Record();
        if(StringUtil.isNotEmpty(id_)){
            record = Db.findById("t_gl_cate","id_",id_);
        }

        String parentId = getPara("parentId","");
        record.set("depth_",1);
        if(StringUtil.isNotEmpty(parentId)){
            record.set("depth_",2);
        }
        record.set("image_url_",getPara("imageUrl")).set("is_show_","online_store")
                .set("name_",getPara("name_")).set("parent_id_",parentId).set("type_key_","ProductCate");
        if(StringUtil.isNotEmpty(id_)){
            if(StringUtil.isNotEmpty(parentId)){
                record.set("path_",parentId+","+id_);
            }else{
                record.set("path_",id_);
            }
            Db.update("t_gl_cate","id_",record);
        }else{
            Long cateId = TGlCateUtil.getId();
            record.set("id_",cateId);
            if(StringUtil.isNotEmpty(parentId)){
                record.set("path_",parentId+","+cateId);
            }else{
                record.set("path_",cateId);
            }
            Db.save("t_gl_cate","id_",record);
        }

        renderJson(new JsonResult().status("000").show("保存成功"));
    }

    /**
     * 删除功能，当前分类下存在商品时不允许删除操作。
     */
    @Before(Tx.class)
    public void batchDelete(){
        String categoryIdList = this.getPara("selectRowList");

        if(StringUtil.isEmpty(categoryIdList)){
            renderJson(new JsonResult().status("001").show("未正确选择分类，请联系管理员"));
            return;
        }

        String[] categoryIdArr = categoryIdList.split(",");

        // 单条删除
        if(categoryIdArr.length == 1){
            // 查询商品分类下的商品数量
            String id = categoryIdArr[0];
            Long prodNumBelongToCategory = Db.queryLong("select count(1) from t_gl_cate a INNER JOIN t_prod_entity b on a.id_ = b.sub_cate_id_ where a.id_ = ?", id);

            if(prodNumBelongToCategory > 0){
                renderJson(new JsonResult().status("001").show("该分类下仍存在商品，无法删除"));
                return;
            }else{
                Db.deleteById("t_gl_cate", "id_", id);
                renderJson(new JsonResult().status("000").show("操作成功"));
                return;
            }
        }else{ // 批量删除
            for(String id : categoryIdArr){
                Long prodNumBelongToCategory = Db.queryLong("select count(1) from t_gl_cate a INNER JOIN t_prod_entity b on a.id_ = b.sub_cate_id_ where a.id_ = ?", id);

                if(!(prodNumBelongToCategory > 0)){
                    Db.deleteById("t_gl_cate", "id_", id);
                }
            }
            renderJson(new JsonResult().status("000").show("操作成功"));
        }
    }

}
